{
  "cells": [
    {
      "cell_type": "code",
      "execution_count": null,
      "id": "0081a036",
      "metadata": {},
      "outputs": [],
      "source": [
        "import numpy as np\n",
        "a = np.arange(15).reshape(3, 5)\n",
        "a\n",
        "a.shape\n",
        "a.ndim\n",
        "a.dtype.name\n",
        "a.itemsize\n",
        "a.size\n",
        "type(a)\n",
        "b = np.array([6, 7, 8])\n",
        "b\n",
        "type(b)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "id": "b4dc129e",
      "metadata": {},
      "outputs": [],
      "source": [
        "import numpy as np\n",
        "a = np.array([2, 3, 4])\n",
        "a\n",
        "a.dtype\n",
        "b = np.array([1.2, 3.5, 5.1])\n",
        "b.dtype"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "id": "6eb2bf6a",
      "metadata": {},
      "outputs": [],
      "source": [
        "b = np.array([[1.5, 2, 3], [4, 5, 6]])\n",
        "b.dtype\n",
        "\n",
        "c = np.array([[1, 2], [3, 4]], dtype=complex)\n",
        "c\n",
        "\n",
        "np.zeros((3, 4))\n",
        "np.ones((2, 3, 4), dtype=np.int16)\n",
        "\n",
        "np.empty((2, 3)) \n",
        "\n",
        "np.arange(10, 30, 5)\n",
        "np.arange(0, 2, 0.3)  # it accepts float arguments\n",
        "\n",
        "from numpy import pi\n",
        "np.linspace(0, 2, 9)                   # 9 numbers from 0 to 2\n",
        "x = np.linspace(0, 2 * pi, 100)        # useful to evaluate function at lots of points\n",
        "# f = np.sin(x)\n",
        "\n",
        "\n",
        "\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "id": "7787612c",
      "metadata": {},
      "outputs": [],
      "source": [
        "a = np.arange(6)                    # 1d array\n",
        "print(a)\n",
        "b = np.arange(12).reshape(4, 3)     # 2d array\n",
        "print(b)\n",
        "c = np.arange(24).reshape(2, 3, 4)  # 3d array\n",
        "print(c)\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "id": "b3ce4936",
      "metadata": {},
      "outputs": [],
      "source": [
        "a = np.array([20, 30, 40, 50])\n",
        "b = np.arange(4)\n",
        "b\n",
        "c = a - b\n",
        "c\n",
        "b**2\n",
        "10 * np.sin(a)\n",
        "a < 35"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "id": "7f6cbd62",
      "metadata": {},
      "outputs": [],
      "source": [
        "rg = np.random.default_rng(1)  # create instance of default random number generator\n",
        "a = np.ones((2, 3), dtype=int)\n",
        "b = rg.random((2, 3))\n",
        "a *= 3\n",
        "a\n",
        "b += a\n",
        "b\n",
        "# a += b  # b is not automatically converted to integer type"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "id": "f66cc327",
      "metadata": {},
      "outputs": [],
      "source": [
        "# 当操作不同类型的数组时，结果数组的类型对应于更通用或更精确的类型（这种行为称为向上转型）\n",
        "a = np.ones(3, dtype=np.int32)\n",
        "b = np.linspace(0, pi, 3)\n",
        "b.dtype.name\n",
        "c = a + b\n",
        "c\n",
        "c.dtype.name\n",
        "d = np.exp(c * 1j)\n",
        "d\n",
        "d.dtype.name"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "id": "084fcad6",
      "metadata": {},
      "outputs": [],
      "source": [
        "a = rg.random((2, 3))\n",
        "a\n",
        "a.sum()\n",
        "a.min()\n",
        "a.max()"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "id": "a5d82c99",
      "metadata": {},
      "outputs": [],
      "source": [
        "b = np.arange(12).reshape(3, 4)\n",
        "b\n",
        "b.sum(axis=0)     # sum of each column\n",
        "b.min(axis=1)     # min of each row\n",
        "b.cumsum(axis=1)  # cumulative sum along each row"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "id": "a3b9b605",
      "metadata": {},
      "outputs": [],
      "source": [
        "B = np.arange(3)\n",
        "B\n",
        "np.exp(B)\n",
        "np.sqrt(B)\n",
        "C = np.array([2., -1., 4.])\n",
        "np.add(B, C)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "id": "37b9e80c",
      "metadata": {},
      "outputs": [],
      "source": [
        "# 一维数组可以被索引、切片和迭代，就像 列表 和其他 Python 序列一样。\n",
        "a = np.arange(10)**3\n",
        "a\n",
        "a[2]\n",
        "a[2:5]\n",
        "# equivalent to a[0:6:2] = 1000;\n",
        "# from start to position 6, exclusive, set every 2nd element to 1000\n",
        "a[:6:2] = 1000\n",
        "a\n",
        "a[::-1]  # reversed a\n",
        "for i in a:\n",
        "    print(i**(1 / 3.))\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "id": "766a6bf0",
      "metadata": {},
      "outputs": [],
      "source": [
        "\n",
        "#多维数组每个轴可以有一个索引。这些索引以逗号​​分隔的元组形式给出：\n",
        "def f(x, y):\n",
        "    return 10 * x + y\n",
        "b = np.fromfunction(f, (5, 4), dtype=int)\n",
        "b\n",
        "b[2, 3]\n",
        "b[0:5, 1]  # each row in the second column of b\n",
        "b[:, 1]    # equivalent to the previous example\n",
        "b[1:3, :]  # each column in the second and third row of b"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "id": "1bae8df9",
      "metadata": {},
      "outputs": [],
      "source": [
        "c = np.array([[[  0,  1,  2],  # a 3D array (two stacked 2D arrays)\n",
        "               [ 10, 12, 13]],\n",
        "              [[100, 101, 102],\n",
        "               [110, 112, 113]]])\n",
        "c.shape\n",
        "c[1, ...]  # same as c[1, :, :] or c[1]\n",
        "c[..., 2]  # same as c[:, :, 2]"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "id": "2c5659ad",
      "metadata": {},
      "outputs": [],
      "source": [
        "for element in b.flat:\n",
        "    print(element)\n",
        "\n",
        "\n",
        "for element in b:\n",
        "    print(element)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "id": "b887d0d2",
      "metadata": {},
      "outputs": [],
      "source": [
        "a = np.arange(12)**2  # the first 12 square numbers\n",
        "print(a) \n",
        "i = np.array([1, 1, 3, 8, 5])  # an array of indices\n",
        "a[i]  # the elements of `a` at the positions `i`\n",
        "j = np.array([[3, 4], [9, 7]])  # a bidimensional array of indices\n",
        "a[j]  # the same shape as `j`"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "id": "5adf25ce",
      "metadata": {},
      "outputs": [],
      "source": [
        "palette = np.array([[0, 0, 0],         # black\n",
        "                    [255, 0, 0],       # red\n",
        "                    [0, 255, 0],       # green\n",
        "                    [0, 0, 255],       # blue\n",
        "                    [255, 255, 255]])  # white\n",
        "image = np.array([[0, 1, 2, 0],  # each value corresponds to a color in the palette\n",
        "                  [0, 3, 4, 0]])\n",
        "palette[image]  # the (2, 4, 3) color image\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "id": "8adae672",
      "metadata": {},
      "outputs": [],
      "source": [
        "a = np.arange(12).reshape(3, 4)\n",
        "print('a = ',a)\n",
        "i = np.array([[0, 1],  # indices for the first dim of `a`\n",
        "              [1, 2]])\n",
        "j = np.array([[2, 1],  # indices for the second dim\n",
        "              [3, 3]])\n",
        "print('a[i, j] =',a[i, j])  # i and j must have equal shape\n",
        "print('a[i, 2] = ',a[i, 2])\n",
        "print('a[:, j] = ',a[:, j])\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "id": "b4eac9ba",
      "metadata": {},
      "outputs": [],
      "source": [
        "import numpy as np\n",
        "import matplotlib.pyplot as plt\n",
        "def mandelbrot(h, w, maxit=20, r=2):\n",
        "    \"\"\"Returns an image of the Mandelbrot fractal of size (h,w).\"\"\"\n",
        "    x = np.linspace(-2.5, 1.5, 4*h+1)\n",
        "    y = np.linspace(-1.5, 1.5, 3*w+1)\n",
        "    A, B = np.meshgrid(x, y)\n",
        "    C = A + B*1j\n",
        "    z = np.zeros_like(C)\n",
        "    divtime = maxit + np.zeros(z.shape, dtype=int)\n",
        "    for i in range(maxit):\n",
        "        z = z**2 + C\n",
        "        diverge = abs(z) > r                    # who is diverging\n",
        "        div_now = diverge & (divtime == maxit)  # who is diverging now\n",
        "        divtime[div_now] = i                    # note when\n",
        "        z[diverge] = r                          # avoid diverging too much\n",
        "    return divtime\n",
        "plt.clf()\n",
        "plt.imshow(mandelbrot(400, 400))"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "id": "b3c102b0",
      "metadata": {},
      "outputs": [],
      "source": [
        "a = np.arange(12).reshape(3, 4)\n",
        "print('a = ',a)\n",
        "b1 = np.array([False, True, True])         # first dim selection\n",
        "b2 = np.array([True, False, True, False])  # second dim selection\n",
        "a[b1, :]                                   # selecting rows\n",
        "a[b1]                                      # same thing\n",
        "a[:, b2]                                   # selecting columns\n",
        "a[b1, b2]                                  # a weird thing to do"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "id": "1ce4fd5f",
      "metadata": {},
      "outputs": [],
      "source": [
        "a = np.array([1, 2, 3, 4, 5, 6])\n",
        "a.shape\n",
        "a2 = a[np.newaxis, :]\n",
        "a2.shape\n",
        "row_vector = a[np.newaxis, :]\n",
        "row_vector.shape\n",
        "row_vector\n",
        "col_vector = a[:, np.newaxis]\n",
        "col_vector.shape\n",
        "b = np.expand_dims(a, axis=1)\n",
        "b.shape"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "id": "9256c0ad",
      "metadata": {},
      "outputs": [],
      "source": []
    }
  ],
  "metadata": {
    "kernelspec": {
      "display_name": "myenv",
      "language": "python",
      "name": "python3"
    },
    "language_info": {
      "codemirror_mode": {
        "name": "ipython",
        "version": 3
      },
      "file_extension": ".py",
      "mimetype": "text/x-python",
      "name": "python",
      "nbconvert_exporter": "python",
      "pygments_lexer": "ipython3",
      "version": "3.10.18"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 5
}